package com.kfm.goods.service.impl;

import com.github.pagehelper.PageHelper;
import com.kfm.goods.domain.User;
import com.kfm.goods.domain.UserDTO;
import com.kfm.goods.ex.ServiceException;
import com.kfm.goods.mapper.UserMapper;
import com.kfm.goods.service.UserService;
import com.kfm.goods.util.Constant;
import com.kfm.goods.util.MD5Util;
import com.kfm.goods.util.UUIDUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;
import org.springframework.util.StringUtils;

import java.util.List;

@Service
public class UserServiceImpl implements UserService {

    @Autowired
    private UserMapper userMapper;

    @Override
    public User login(User user) throws ServiceException {
        // 校验参数
        if (ObjectUtils.isEmpty(user) || !StringUtils.hasText(user.getUsername()) || !StringUtils.hasText(user.getPassword())) {
            throw new ServiceException("用户名或密码不能为空");
        }

        // 密码加密
        String password = MD5Util.encodePassword(user.getPassword(), user.getUsername());
        user.setPassword(password);

        // 查询数据库
        List<User> users = userMapper.selectAll(user);

        // 判断是否查询到结果
        if (users.size() == 1) {
            // 用户名密码正确的
            User u = users.get(0);

            // 判断状态
            if (u.getState() == 1){
                return u;
            }
            throw new ServiceException("用户已被禁用");
        }
        throw new ServiceException(Constant.USERNAME_PASSWORD_ERROR_CODE, "用户名或密码错误");
    }

    @Override
    public List<UserDTO> findAll(int page, int pageSize, User user) throws ServiceException {
        PageHelper.startPage(page, pageSize);
        List<UserDTO> users = userMapper.selectWithDept(user);
        return users;
    }

    @Override
    public User findById(String id) {
        return userMapper.selectByPrimaryKey(id);
    }

    @Override
    public void update(User user) throws ServiceException {
        if (ObjectUtils.isEmpty(user)){
            throw new ServiceException("用户不能为空");
        }

        int row = 0;
        if (!StringUtils.hasText(user.getId())){
            // 新增
            user.setId(UUIDUtil.uuid32());
            // 密码加密
            String password = MD5Util.encodePassword(user.getPassword(), user.getUsername());
            user.setPassword(password);

            // 数据库用户名做了唯一约束，所以此处省略验证用户名是否存在
            row = userMapper.insertSelective(user);
        }else {
            row = userMapper.updateByPrimaryKeySelective(user);
        }
        if (row != 1){
            throw new ServiceException("更新失败");
        }
    }
}
